package com.ruoyi.riskrule.config.step1;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.bizsys.service.IExtIdentityResultService;
import com.ruoyi.common.VersionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.riskrule.config.common.DeviceFingerprintEnum;
import com.ruoyi.riskrule.service.ICreditFieldService;
import com.ruoyi.riskrule.service.ILoanFieldService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Configuration
@AllArgsConstructor
@Slf4j
public class DerivedParamsLoader {

    private ICreditFieldService creditService;
    private ILoanFieldService loanService;
    private IAppUserService appUserService;
    private IExtIdentityResultService iExtIdentityResultService;

    /**
     * 为ruleIn填充DeviceInfo数据-衍生字段
     * @param ruleIn
     * @param appDeviceInfo
     */
    public void setRuleInByDeviceInfoDerived(RuleIn ruleIn, AppDeviceInfo appDeviceInfo){
//        System.out.println(appDeviceInfo);
//        System.out.println(appDeviceInfo.getFingerprint());
//        System.out.println(ruleIn);

        int cntDevice = creditService.getCntDevice(appDeviceInfo.getFingerprint());
        System.out.println(cntDevice);

        ruleIn.setCntDevice(creditService.getCntDevice(appDeviceInfo.getFingerprint()) + "");

        if (StringUtils.isNotBlank(appDeviceInfo.getWifiName()) && !StringUtils.equalsAny(appDeviceInfo.getWifiName(), "<unknown ssid>", "0x")) {
            int cntwifino = creditService.getCntwifino(appDeviceInfo.getWifiName(), appDeviceInfo.getCountryState());
            ruleIn.setCntwifino(cntwifino + "");
            int cntwifiodno = creditService.getCntwifiodno(appDeviceInfo.getWifiName(), appDeviceInfo.getCountryState());
            ruleIn.setCntwifiodno(cntwifiodno + "");
        }

        String lon = "";
        String lat = "";

        if (StringUtils.isNotBlank(appDeviceInfo.getLongitude()) && StringUtils.isNotBlank(appDeviceInfo.getLatitude())) {
            String[] lonSp = appDeviceInfo.getLongitude().split("\\.");
            String[] latSp = appDeviceInfo.getLatitude().split("\\.");
            if (lonSp.length == 2 && latSp.length == 2) {
                if (lonSp[1].length() > 4) {
                    lonSp[1] = lonSp[1].substring(0, 4);
                }
                if (latSp[1].length() > 4) {
                    latSp[1] = latSp[1].substring(0, 4);
                }

                lon = lonSp[0] + "." + lonSp[1];
                lat = latSp[0] + "." + latSp[1];

                int cntgpsno = creditService.getCntgpsno(lon, lat);
                ruleIn.setCntgpsno(cntgpsno + "");
                int cntgpsodno = creditService.getCntgpsodno(lon, lat);
                ruleIn.setCntgpsodno(cntgpsodno + "");
            }
        }

        //Imei关系客户数
        if (Func.isNotEmpty(appDeviceInfo.getImei())) {
            int imeiCutCount = creditService.getImeiCutCount(Func.toStrArray(appDeviceInfo.getImei()));
            ruleIn.setCntImei(imeiCutCount + "");
        }

        //客户第一次解析成功不为空的州
        ruleIn.setFristcountrystate(creditService.getFristcountrystate(appDeviceInfo.getUserId()));

        //同新老设备指纹关联的客户当前逾期数
        //客户在授信和交易环节使用的新旧设备指纹去重数
        if (!StringUtils.equalsAny(appDeviceInfo.getFingerprint(), "{}", "", null)) {
            ruleIn.setDeviceAllUserOverdueFlag(loanService.getFingerprintCustOverdueNum(appDeviceInfo.getFingerprint()) + "");
            ruleIn.setCntDeviceApply(creditService.custNumByFingerprint(appDeviceInfo.getUserId()) + "");
        }

        //判断首次是否旧版本且当前版本是新版本   true -> app_device_fingerprint, false -> app_device_info
        if (!Func.isEmpty(appDeviceInfo.getAppVersion())) {
            String deviceTable = devicePedal(appDeviceInfo.getUserId(), appDeviceInfo.getAppVersion());
            String deviceType = DeviceFingerprintEnum.getV(appDeviceInfo.getDeviceidType());

            if (!StringUtils.equalsAny(appDeviceInfo.getNewFingerprint(), "{}", "", null)) {

                //同新设备指纹关联的客户当前逾期数
                ruleIn.setNewDeviceAllUserOverdue(loanService.getNewFingerprintCustOverdueNum(appDeviceInfo.getFingerprint(), deviceTable, deviceType) + "");
                //客户在授信和交易环节使用的新设备指纹去重数
                ruleIn.setCntNewDeviceApply(creditService.custNumByNewFingerprint(ruleIn.getCustNo(), deviceTable, deviceType) + "");
                //新设备关联客户数
                ruleIn.setCntdevicenew(creditService.fingerprintRelationCustNum(appDeviceInfo.getNewFingerprint(), deviceTable, deviceType));
            }

            //客户使用过的新设备指纹去重数
            ruleIn.setCntnewdevicetotal(creditService.getUseDistinctNewFingerprint(ruleIn.getCustNo(), deviceTable, deviceType) + "");
        }
    }

    public void setRuleInByCustomerDataDerived(RuleIn ruleIn){
        ruleIn.setCstMcntMail(creditService.getCstMcntMail(ruleIn.getEmail()) + "");
        ruleIn.setCntcontact1(creditService.getCntcontactRelation(ruleIn.getContactmobile()));
        ruleIn.setCntcontact2(creditService.getCntcontactRelation(ruleIn.getEmcontactnum()));
    }

    public void setRuleInByRealNameDerived(RuleIn ruleIn, RealNameAuth realName){
        ruleIn.setCntBvn(creditService.getCntBvn(realName.getPhoneNumber()) + "");

        QueryWrapper<ExtIdentityResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bvn",realName.getBvnAccount());
        queryWrapper.eq("state","1");
        queryWrapper.eq("user_id",ruleIn.getCustNo()).last("order by id asc limit 1");
        ExtIdentityResult one = iExtIdentityResultService.getOne(queryWrapper);
        String kycbirthmatch = getKycbirthmatch(one, realName);
        ruleIn.setKycbirthmatch(kycbirthmatch);
    }

    public void setRuleInByAppUserDerived(RuleIn ruleIn,AppUser appUser){
        //推荐人逾期？
        ruleIn.setInviterOverdueFlag("0");
        if (StringUtils.isNotBlank(appUser.getRecommendCode())) {
            AppUser inviteUser = new AppUser();
            inviteUser.setInviteCode(appUser.getRecommendCode());
            //inviteUser.setState(UserConstants.NORMAL);
            List<AppUser> inviteUserList = appUserService.selectAppUserList(inviteUser);
            if (!CollectionUtils.isEmpty(inviteUserList)) {
                ruleIn.setInviterOverdueFlag(creditService.getOverdueFlagByUserId(inviteUserList.get(0).getUserUuid()));
            }
        }

        //渠道
        ruleIn.setChannel(appUser.getChannel());
        //CRS 批次
        ruleIn.setStageResult(StringUtils.isEmpty(appUser.getStageResult()) ? "-1": appUser.getStageResult());
        log.info("批次号{}",appUser.getStageResult());
        if (Func.isNotEmpty(appUser.getRecommendCode())) {
            AppUser appUserQ = new AppUser();
            appUserQ.setInviteCode(appUser.getRecommendCode());
            appUserQ.setInviteCodeStatus("1");
            List<AppUser> recommendUsers = appUserService.selectAppUserList(appUserQ);
            //邀请码用户存在且邀请码有效
            ruleIn.setInvitedbynet(recommendUsers.size() > 0 ? "1" : "0");
        }

    }
    /**
     * @param userId
     * @param currentVersion
     * @return true -> app_device_fingerprint, false -> app_device_info
     */
    private String devicePedal(String userId, String currentVersion) {
        String firstVersion = creditService.getDeviceFirstVersion(userId);
        //true -> 旧版本
        boolean firstRes = Func.isEmpty(firstVersion) || VersionUtils.compareVersion(firstVersion, "2.1.2") < 0;
        //新 -> 新
        if (!firstRes) {
            return "app_device_info";
        }
        boolean currentRes = Func.isEmpty(currentVersion) || VersionUtils.compareVersion(currentVersion, "2.1.2") >= 0;
        //旧 -> 新
        if (firstRes && currentRes) {
            return "app_device_fingerprint";
        }
        //旧 -> 旧
        return "app_device_info";
    }

    public String getKycbirthmatch(ExtIdentityResult extIdentityResult,RealNameAuth realName){
        if(extIdentityResult==null || StringUtils.isBlank(extIdentityResult.getDob())){
            //返回值为空
            return "4";
        }else{
            String[] dobArr = extIdentityResult.getDob().split(",");
            boolean dobEquals = false;
            for (int i = 0; i < dobArr.length; i++) {
                if (StringUtils.equals(DateUtils.multipleParse(realName.getBirthDate(),DateUtils.DD_MM_YYYY), DateUtils.multipleParse(dobArr[i],DateUtils.DD_MM_YYYY))){
                    //完全匹配
                    return  "1";
                }
                if (StringUtils.equals(DateUtils.multipleParse(realName.getBirthDate(),DateUtils.MM_YYYY), DateUtils.multipleParse(dobArr[i],DateUtils.MM_YYYY))){
                    dobEquals = true;
                }
            }
            if(dobEquals){
                //年月匹配
                return "2";
            }else{
                //不匹配
                return "3";
            }
        }
    }

}
